package com.ruoyi.cs.service;

import com.alibaba.fastjson.JSON;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.ruoyi.common.config.TC_COS_Config;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import org.apache.commons.lang3.RandomUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Base64;
import java.util.UUID;

/**
 * 图片上传服务
 * 上传至腾讯云COS(对象存储中心)
 */
@Service
@SuppressWarnings("all")
public class PicUploadService {

    @Autowired
    private COSClient cosClient;

    @Autowired
    private TC_COS_Config tc_cos_config;

    public String upload(MultipartFile uploadFile) throws Exception{
        // 校验图片格式
        this.checkFileFormat(uploadFile, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        // 文件新路径
        String filePath =  FileUploadUtils.extractFilename(uploadFile);
        //上传文件

        // 指定要上传到的存储桶
        String bucketName = tc_cos_config.getBucketName();
        // 指定要上传到 COS 上对象键
        String key = tc_cos_config.getFileUrl()+filePath;
        PutObjectResult putObjectResult = cosClient.putObject(bucketName,key,new ByteArrayInputStream(uploadFile.getBytes()),null);
        //设置输出信息
        System.out.println(JSON.toJSON(putObjectResult));
        String fileUrl = this.tc_cos_config.getPath()+key;
        return  fileUrl;
     }

    public String uploadByte(String base) throws Exception{
        // 文件新路径
        String fileName =UUID.randomUUID().toString() + ".jpg";
        // 指定要上传到的存储桶
        String bucketName = tc_cos_config.getBucketName();
        // 指定要上传到 COS 上对象键
        String key = tc_cos_config.getFileUrl()+"/"+fileName;;
        byte[] bytes = Base64.getDecoder().decode(base);
        ObjectMetadata metadata = new ObjectMetadata();
        PutObjectResult putObjectResult = cosClient.putObject(bucketName,key,new ByteArrayInputStream(bytes),metadata);
        //设置输出信息
        System.out.println(JSON.toJSON(putObjectResult));
        String fileUrl = this.tc_cos_config.getPath()+key;
        return  fileUrl;
    }
    /**
     * 生成文件路径
     * @param sourceFileName
     * @return
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/"
                + dateTime.toString("yyyy") + "/" + dateTime.toString("MM")
                + "/" + dateTime.toString("dd")
                + "/" + System.currentTimeMillis()
                + RandomUtils.nextInt(100, 9999) + "."
                + StringUtils.substringAfterLast(sourceFileName, ".");
    }

    /**
     * 交易图片文件
     * @param uploadFile
     */
    private void checkFileFormat(MultipartFile uploadFile,String[] allowedExtension) throws InvalidExtensionException {
        int fileNamelength = uploadFile.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        FileUploadUtils.assertAllowed(uploadFile, allowedExtension);
    }

    public String uploadFile(File file) throws Exception{
        // 文件新路径
        String fileName = DateUtils.dateTimeNow()+ UUID.randomUUID().toString() + ".jpg";
        // 指定要上传到的存储桶
        String bucketName = tc_cos_config.getBucketName();
        // 指定要上传到 COS 上对象键
        String key = tc_cos_config.getFileUrl()+fileName;;
        ObjectMetadata metadata = new ObjectMetadata();
        PutObjectResult putObjectResult = cosClient.putObject(bucketName,key,file);
        //设置输出信息
        String fileUrl = this.tc_cos_config.getPath()+key;
        return  fileUrl;
    }
}
